package com.sx.pipeline.qqlogin

import android.app.Activity
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.sx.mvvmlibs.base.BaseApp
import com.sx.mvvmlibs.bus.RxBus
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.app.event.QQLoginEvent
import com.tencent.connect.UserInfo
import com.tencent.tauth.DefaultUiListener
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import org.json.JSONObject

/**
 * @Author: YY
 * @Date: 2022/8/1
 * @Desc: TODO
 */
open class BaseUIListener(private val mTencent: Tencent): IUiListener {

    override fun onComplete(response: Any?) {
        Logs.d("onComplete")
        if (response == null) {
            ToastUtils.showShort("返回为空,登录失败")
            return
        }
        val jsonResponse = response as JSONObject
        if (jsonResponse.length() == 0) {
            ToastUtils.showShort("返回为空,登录失败")
            return
        }
        doComplete(response)
        getQQInfo()
    }

    override fun onError(p0: UiError?) {
        ToastUtils.showShort("授权失败")
    }

    override fun onCancel() {
        ToastUtils.showShort("取消授权")
    }

    override fun onWarning(p0: Int) {

    }

    private fun doComplete(values: JSONObject?) {
        val gson = Gson()
        val qqLogin = gson.fromJson(values.toString(), QQLogin::class.java)
        mTencent.setAccessToken(qqLogin.access_token, qqLogin.expires_in.toString())
        mTencent.openId = qqLogin.openid
    }

    private fun getQQInfo() {
        val qqToken = mTencent.qqToken
        val info = UserInfo(BaseApp.getInstance(), qqToken)

        info.getUserInfo(object : IUiListener {
            override fun onComplete(response: Any?) {
                Logs.d("getUserInfo onComplete ${mTencent.openId}")
                RxBus.getDefault().post(QQLoginEvent(mTencent.accessToken, mTencent.openId))
            }

            override fun onError(p0: UiError?) {

            }

            override fun onCancel() {

            }

            override fun onWarning(p0: Int) {

            }

        })
    }

}